package com.ficv.tucanalmovil;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.ads.AdView;

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.ficv.tucanalmovil.MESSAGE";
//	public static final String URL_BASE = "http://www.uco.es/~i42cavif/android/";
//	public static final String URL_BASE = "http://tucanalmovil.jelastic.dogado.eu/dev/";
//	public static final String URL_BASE = "http://192.168.2.169:8080/tucanalmovil/dev/";
//	public static final String URL_BASE = "http://192.168.43.131:8080/tucanalmovil/dev/";
	
//    public static final String URL_BASE = "http://www.uco.es/~i42cavif/android/urlbase";
//	public static final String URL_BASE = "http://10.42.0.1:8080/tucanalmovil/devices/url";
	public static final String URL_BASE = "http://192.168.2.141:8080/tucanalmovil/devices/url";
//	public static final String URL_BASE = "http://192.168.43.131:8080/tucanalmovil/devices/url";

	
	private AdView adView;
    
    
    @Override
    public void onDestroy() {
      if (adView != null) {
        adView.destroy();
      }
      super.onDestroy();
    }
    
    private final String FILENAME = "codigo.cod";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
//        ProgressDialog dialog = ProgressDialog.show(this,  "Cargando", "Tu canal móvil");            
        Toast.makeText(this, "Cargando...", Toast.LENGTH_LONG).show();
        String code=null;
        
        try {
	        FileInputStream fis = openFileInput(FILENAME);
	        DataInputStream in = new DataInputStream(fis);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
	        String strLine;
	        //Read File Line By Line
	        while ((strLine = br.readLine()) != null) {
	        	code=strLine;
	        }
	        //Close the input stream
	        in.close();
        }catch (Exception e){//Catch exception if any
        	System.err.println("Error: " + e.getMessage());
        }
        
        startService(new Intent(MiService.class.getName()));
        
        if(code!=null && code.length()>0) { 
            Intent intent = new Intent(this, DisplayMessageActivity.class);
            intent.putExtra(EXTRA_MESSAGE, code);
            startActivity(intent);
            finish();
        }
        else {
        	setContentView(R.layout.activity_main);
        }
        
      
        
//        adView = new AdView(this, AdSize.BANNER, "a1502e279012010");
//
//        // Lookup your LinearLayout assuming it's been given
//        // the attribute android:id="@+id/mainLayout"
//        LinearLayout layout = (LinearLayout)findViewById(R.id.ad_layout);
//
//        // Add the adView to it
//        layout.addView(adView);
//
//        // Initiate a generic request to load it with an ad
//        adView.loadAd(new AdRequest());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }



    
    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
//        EditText editText = new EditText(this);

        

        
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        
//        editText.setText(metrics.heightPixels + ", " + metrics.widthPixels + ", " + metrics.densityDpi );
//        
        

        FileOutputStream fos;
		try {
			fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
	        fos.write(message.getBytes());
	        fos.close();
		} catch (Throwable e) {

			e.printStackTrace();
		}

        
        startActivity(intent);
    	//Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
    	//Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

//    	Uri number = Uri.parse("tel:645849973");
//    	Intent callIntent = new Intent(Intent.ACTION_CALL, number);
//    	// Verify it resolves
//    	PackageManager packageManager = getPackageManager();
//    	List<ResolveInfo> activities = packageManager.queryIntentActivities(callIntent, 0);
//    	boolean isIntentSafe = activities.size() > 0;
//    	  
//    	// Start an activity if it's safe
//    	if (isIntentSafe) {
//    	    startActivity(callIntent);
//    	}
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_settings:
            newGame();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

	private void newGame() {
//    	Uri number = Uri.parse("http://www.uco.es");
//    	Intent callIntent = new Intent(Intent.ACTION_VIEW, number);
    	// Verify it resolves
		
		Intent emailIntent = new Intent(Intent.ACTION_SEND);
		// The intent does not have a URI, so declare the "text/plain" MIME type
		emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
		emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"francisco.isaac@gmail.com"}); // recipients
		emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contacto");
		emailIntent.putExtra(Intent.EXTRA_TEXT, "Desearía obtener un código para la demo de tucanalmovil");

    	PackageManager packageManager = getPackageManager();
    	List<ResolveInfo> activities = packageManager.queryIntentActivities(emailIntent, 0);
    	boolean isIntentSafe = activities.size() > 0;
    	  
    	// Start an activity if it's safe
    	if (isIntentSafe) {
    	    startActivity(emailIntent);
    	} else {
            Toast.makeText(this, "Escriba a francisco.isaac@gmail.com", Toast.LENGTH_LONG).show();
    	}
	}

}
